import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:info_ca/bean/hostModel.dart';
import 'package:info_ca/bean/userModel.dart';

// ignore: camel_case_types
class LoginPage extends StatefulWidget {
  const LoginPage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  late String _username, _password;
  String loginMsg = "";
  int code = 0;
  String host = HostModel.ipHost;
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;
  String _responseBody = "";
  final List _loginMethod = [
    {
      "title": "facebook",
      "icon": Icons.facebook,
    },
    {
      "title": "google",
      "icon": Icons.fiber_dvr,
    },
    {
      "title": "twitter",
      "icon": Icons.account_balance,
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey, // 设置globalKey，用于后面获取FormStat
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          children: [
            const SizedBox(
                height:
                    kToolbarHeight), // 距离顶部一个工具栏的高度info_ca/lib/widgets/login.dart
            buildTitle(), // Login
            buildTitleLine(), // Login下面的下划线
            const SizedBox(height: 60),
            buildAccountTextField(), // 输入邮箱
            const SizedBox(height: 30),
            buildPasswordTextField(context), // 输入密码
            buildForgetPasswordText(context), // 忘记密码
            const SizedBox(height: 60),
            buildLoginButton(context), // 登录按钮
            const SizedBox(height: 20),
            buildRegisterText(context), // 注册
            const SizedBox(height: 6),
            buildOtherMethod(context), // 其他登录方式
            buildOtherLoginText(), // 其他账号登录
          ],
        ),
      ),
    );
  }

  Widget buildRegisterText(context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(top: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('没有账号?'),
            GestureDetector(
              child: const Text('点击注册', style: TextStyle(color: Colors.green)),
              onTap: () {
                Navigator.pushNamed(context, "/register");
                print("点击注册");
              },
            ),
            SizedBox(width: 20,),
            GestureDetector(
              child: const Text('游客登录', style: TextStyle(color: Colors.blue)),
              onTap: () {
                print("游客登录");
              },
            )
          ],
        ),
      ),
    );
  }

  Widget buildOtherMethod(context) {
    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: _loginMethod
          .map((item) => Builder(builder: (context) {
                return IconButton(
                    icon: Icon(item['icon'],
                        color: Theme.of(context).iconTheme.color),
                    onPressed: () {
                      //TODO: 第三方登录方法
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                            content: Text('${item['title']}登录'),
                            action: SnackBarAction(
                              label: '取消',
                              onPressed: () {},
                            )),
                      );
                    });
              }))
          .toList(),
    );
  }

  Widget buildOtherLoginText() {
    return const Center(
      child: Text(
        '其他账号登录',
        style: TextStyle(color: Colors.grey, fontSize: 14),
      ),
    );
  }

  void login() async {
    try {
      // 发送 POST 请求
      final response = await http.post(
        Uri.parse('http://$host/user/login'),
        body: {'Username': _username, 'Password': _password},
      );
      if (response.statusCode == 200) {
        setState(() {
          final _responseBody = jsonDecode(response.body);
          if (_responseBody['code'] == 200) {
            UserModel.token = _responseBody['result']['token'];
            loginMsg = _responseBody['msg'];
            code = _responseBody['code'];
          } else {
            loginMsg = _responseBody['msg'];
            code = _responseBody['code'];
          }
        });
        if (code == 200) {
          Navigator.pushNamed(context, '/home');
        } else {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text(loginMsg),
              content: Text(_responseBody),
              actions: <Widget>[
                TextButton(
                  child: const Text('OK'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                )
              ],
            ),
          );
        }
      } else {
        throw Exception('Failed to make post request');
      }

      // 解析 JSON 格式的响应数据

      // 输出结果
      // print('Code: ${_responseBody['code']}');
      // print('Message: ${_responseBody['msg']}');
      // print('Result: ${_responseBody['result']}');
      // // print('Token: ${data['result']['token']}');
      // print('Time: ${_responseBody['time']}');
    } catch (e) {
      print('Error: $e');
    }
  }

  Widget buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45,
        width: 270,
        child: ElevatedButton(
          style: ButtonStyle(
            shape: MaterialStateProperty.all<RoundedRectangleBorder>(
              RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(4),
              ),
            ),
          ),
          child: Text('登录',
              style: Theme.of(context).primaryTextTheme.headline5),
          onPressed: () {
            // 表单校验通过才会继续执行
            if ((_formKey.currentState as FormState).validate()) {
              (_formKey.currentState as FormState).save();
              //TODO 执行登录方法
              login();
            }
          },
        ),
      ),
    );
  }

  Widget buildForgetPasswordText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Align(
        alignment: Alignment.centerRight,
        child: TextButton(
          onPressed: () {
            // Navigator.pop(context);
            print("忘记密码");
          },
          child: const Text("忘记密码？",
              style: TextStyle(fontSize: 14, color: Colors.grey)),
        ),
      ),
    );
  }

  Widget buildPasswordTextField(BuildContext context) {
    return TextFormField(
        obscureText: _isObscure, // 是否显示文字
        onSaved: (v) => _password = v!,
        validator: (v) {
          if (v!.isEmpty) {
            return '请输入密码';
          }
        },
        decoration: InputDecoration(
            labelText: "密码",
            suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                // 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = (_isObscure
                      ? Colors.grey
                      : Theme.of(context).iconTheme.color)!;
                });
              },
            )));
  }

  Widget buildAccountTextField() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '账户'),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '账号不能为空';
        }
        return null;
      },
      onSaved: (v) => _username = v!,
    );
  }

  Widget buildTitleLine() {
    return Padding(
        padding: const EdgeInsets.only(left: 12.0, top: 4.0),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: Container(
            color: Colors.black,
            width: 40,
            height: 2,
          ),
        ));
  }

  Widget buildTitle() {
    return Row(
      children: [
        const Padding(
            padding: EdgeInsets.all(8),
            child: Text(
              'Login',
              style: TextStyle(fontSize: 42),
            )),
        const Padding(
            padding: EdgeInsets.all(8),
            child: Text(
              'Register',
              style: TextStyle(fontSize: 20),
            )),
      ],
    );
  }
}
